package com.example.order_service.service.impl;

import com.example.order_service.domain.ProductOrder;
import com.example.order_service.service.ProductClient;
import com.example.order_service.service.ProductOrderService;
import com.example.order_service.utils.JsonUtils;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class ProductOrderServiceImpl implements ProductOrderService {

    private ProductClient productClient;

    @Autowired
    public ProductOrderServiceImpl(ProductClient productClient) {
        this.productClient = productClient;
    }

    @Override
    public ProductOrder save(int userId, int productId) {
        String resp = productClient.findById(productId);
        JsonNode jsonNode = JsonUtils.str2JsonNode(resp);
        // 获取商品详情
        ProductOrder productOrder = new ProductOrder();
        productOrder.setCreateTime(new Date());
        productOrder.setUserId(userId);
        productOrder.setTradeNo(UUID.randomUUID().toString());
        if (jsonNode != null) {
            productOrder.setProductName(jsonNode.get("name").toString());
            productOrder.setPrice(Integer.parseInt(jsonNode.get("price").toString()));
        }
        return productOrder;
    }
}
